<?php

namespace App\Exports\WorkOrder;

use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Enums\WorkOrder\MissionEnum;
use App\Enums\WorkOrder\OrderEnum;
use App\Models\Common\ConfigModel;
use App\Models\Common\ResourcesModel;
use App\Models\FuYou\WorkOrderFuyouInfoModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopContractTemplateModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\WorkOrder\WorkOrderApplyContentModel;
use App\Models\WorkOrder\WorkOrderApplyMainModel;
use App\Models\WorkOrder\WorkOrderApplyManagerModel;
use App\Models\WorkOrder\WorkOrderProductCompanyModel;
use App\Models\WorkOrder\WorkOrderUserRoleModel;
use App\Remote\Rms\RmsUserRemote;
use App\Service\WorkOrder\ProblemFeedbackService;
use App\Service\WorkOrder\Web\ProblemFeedbackWebService;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\FromArray;

class FunctionOpenExport implements FromArray
{

    public Collection $originalData;
    public int        $type;
    public Collection $shopInfos;
    public array      $excelHeaders;
    public array      $excelContents;
    public string     $submitTimeStart;
    public string     $submitTimeEnd;
    public array      $problemChildIdsArr;

    public function __construct(
        int $type,
        Collection $originalData,
        Collection $shopInfos,
        string $submitTimeStart,
        string $submitTimeEnd,
        array $problemChildIdsArr
    ) {
        $this->type               = $type;
        $this->originalData       = $originalData;
        $this->shopInfos          = $shopInfos;
        $this->submitTimeStart    = $submitTimeStart;
        $this->submitTimeEnd      = $submitTimeEnd;
        $this->problemChildIdsArr = $problemChildIdsArr;
    }

    public function array(): array
    {
        // TODO: Implement array() method.
        $workOrderNoMap = $this->originalData->pluck("workOrderNo")->unique()->toArray();

        $signOrder = OpenShopSignOrderModel::query()
                                           ->where('status' ,"<>", SignOrderEnum::ORDER_STATUS_NO)
                                           ->with(["identityCardRel", "checkAcceptRel", "contractRel"])
                                           ->whereIn("shopCode",
                                               $this->shopInfos->pluck("shopCode")->unique()->toArray())
                                           ->get();

        $workOrderContentModel = WorkOrderApplyContentModel::query()
                                                           ->whereIn("workOrderNo", $workOrderNoMap)
                                                           ->get();

        $applyManagerMapModel = WorkOrderApplyManagerModel::query()
                                                          ->whereIn("workOrderNo", $workOrderNoMap)
                                                          ->where('role', '>', WorkOrderUserRoleModel::ROLE_TYPE_1)
                                                          ->get();



        $maxFeedback = $applyManagerMapModel->isEmpty() ? 0 : $applyManagerMapModel->groupBy("workOrderNo")->max()
                                                                                   ->count();
        // 工单客服人员
        $workOrderUserRoleList = WorkOrderUserRoleModel::query()
            ->groupBy('userId')
            ->select(['userId', 'name'])
            ->get()->keyBy('userId')->toArray();
        //查询rms用户信息-关联督导
        $councilorIds = $this->shopInfos->pluck("councilorId")->unique()->filter()->toArray();
        $userInfo     = collect($councilorIds ? RmsUserRemote::getRmsUserByIds($councilorIds) : [])->pluck(null, "id");

        $problemChildId = 0;
        $workOrderFuyouInfoModel = [];
        if (count($this->problemChildIdsArr) == 1 && in_array(OrderEnum::PROBLEM_PID_5_CHILDREN_105, $this->problemChildIdsArr)) {//夸父收银进件2.0 导出信息修改
            $problemChildId = OrderEnum::PROBLEM_PID_5_CHILDREN_105;
            //查询富友信息
            $workOrderFuyouInfoModel = WorkOrderFuyouInfoModel::query()
                ->whereIn("workOrderNo", $workOrderNoMap)
                ->get();
        }
        $this->generateExcelHeader($maxFeedback, $problemChildId);

        $this->excelContents = $this->originalData->map(function ($v, $k) use (
            $userInfo,
            $signOrder,
            $workOrderContentModel,
            $applyManagerMapModel,
            $problemChildId,
            $workOrderFuyouInfoModel,
            $workOrderUserRoleList
        ) {
            $shopCode                      = $this->shopInfos[$v->shopId]['shopCode'] ?? '';
            $shopName                      = $this->shopInfos[$v->shopId]['name'] ?? '';
            $actuallySignOrder             = $signOrder->where("shopCode", $shopCode)->first();
            $actuallyWorkOrderContentModel = $workOrderContentModel->where("workOrderNo", $v->workOrderNo)
                                                                   ->first();
            if ($problemChildId == OrderEnum::PROBLEM_PID_5_CHILDREN_105) {//夸父收银进件2.0
                if ($workOrderFuyouInfoModel) {
                    $fuyouInfo = $workOrderFuyouInfoModel->where("workOrderNo", $v->workOrderNo)->first();
                    $tempCommonExcelContents = [
                        date('Y-m-d', $v->createdAt->timestamp),
                        $fuyouInfo ? WorkOrderFuyouInfoModel::DEFAULT_FY_TEXT_STATUS[$fuyouInfo->weChatAuthorizeStatus] : "",
                        $fuyouInfo ? WorkOrderFuyouInfoModel::DEFAULT_FY_TEXT_STATUS[$fuyouInfo->alipayAuthorizeStatus] : "",
                        $fuyouInfo ? WorkOrderFuyouInfoModel::DEFAULT_FY_TEXT_STATUS[$fuyouInfo->secondaryBindingStatus] : "",
                        "是",
                        '',
                        $shopCode . $shopName,
                        $fuyouInfo ? $fuyouInfo->companyName :
                            ($actuallyWorkOrderContentModel ?
                                WorkOrderApplyContentModel::getContent($actuallyWorkOrderContentModel)->get("enterpriseName", "") : ""),
                        $fuyouInfo ? $fuyouInfo->mchName : "",
                        $fuyouInfo ? $fuyouInfo->mchPassword : "",
                        $fuyouInfo ? $fuyouInfo->fyMchntCd : "",
                        $fuyouInfo ? $fuyouInfo->mchKey : "",
                        $fuyouInfo ? $fuyouInfo->orderPrefix : "",
                        OpenShopContractTemplateModel::MODE_MAP_TEXT[attributeGet($actuallySignOrder, "contractRel.mode",0)] ?? "-",
                    ];
                }
            } else {
                $tempCommonExcelContents = [
                    $k + 1,
                    $v->workOrderNo,
                    $v->stepText,
                    $shopCode,
                    $shopName,
                    OpenShopContractTemplateModel::MODE_MAP_TEXT[attributeGet($actuallySignOrder, "contractRel.mode",0)] ?? "-",
                    $actuallySignOrder && $actuallySignOrder->identityCardRel ? $actuallySignOrder->identityCardRel->name : "",
                    date('Y-m-d H:i:s', $v->createdAt->timestamp),
                    $userInfo->get($this->shopInfos[$v->shopId]['councilorId'] ?? 0, [])["username"] ?? "",//门店督导 $actuallySignOrder && $actuallySignOrder->checkAcceptRel ? $actuallySignOrder->checkAcceptRel->managerName : "",
                    $v->problemPidText,
                    $v->problemChildIdText,
                ];
            }
            switch ($this->type) {
                case OrderEnum::PROBLEM_PID_1:
                case OrderEnum::PROBLEM_PID_2:
                    $factoryName = '';//生产厂家
                    //选择问题产品
                    $errJdeCodes = WorkOrderApplyContentModel::getContent($actuallyWorkOrderContentModel)
                        ->get("errJdeCodes", []);
                    $chooseFactory = WorkOrderApplyContentModel::getContent($actuallyWorkOrderContentModel)
                        ->get("chooseFactory", []);
                    $goodsCode    = [];//商品编码
                    $goodsTagName = [];//统一名称
                    if ($errJdeCodes && is_array($errJdeCodes)) {
//                        $tempFactory = [];
                        foreach ($errJdeCodes as $errGoods) {
//                            $tempFactory[] = [
//                                'text'  => $errGoods['supplier_name'] ?? '其他',//供应商名称
//                                'value' => $errGoods['supplier_id'] ?? 0,//供应商id
//                            ];
                            $chooseFactory[] = $errGoods['supplier_id'] ?? 0;
                        }
                        $chooseFactory = array_unique($chooseFactory);
//                        $factoryName = implode(',', array_unique(array_column($tempFactory, 'text')));
                        $goodsCode    = implode(',', array_unique(array_column($errJdeCodes, 'goods_code')));
                        $goodsTagName = implode(',', array_unique(array_column($errJdeCodes, 'tag_name')));
                        $errJdeCodes  = implode(',', array_unique(array_column($errJdeCodes, 'goods_name')));
                    }
                    if ($chooseFactory) {//生产厂家 选择框有数据时
                        $factory     = ProblemFeedbackService::getOrmSupplier();//查询所有厂家信息
                        $factory     = array_column($factory,'text','value');
                        $tempFactory = [];
                        foreach ($chooseFactory as $chooseFactoryValue) {
                            $tempFactory[] = $factory[$chooseFactoryValue] ?? '其他';//供应商名称
                        }
                        $factoryName = implode(',', array_unique($tempFactory));
                    }
                if ($this->type == OrderEnum::PROBLEM_PID_2) {
                    $resources = (array)ResourcesModel::getModuleBusinessResources(
                        ResourcesModel::MODULE_TYPE_WORK_ORDER,
                        ResourcesModel::BUSINESS_WORK_ORDER_PROBLEM_FEEDBACK,
                        $actuallyWorkOrderContentModel->id,
                        ["arrivalNoteImg", "productAbnormalImg", "productInnerLabelImg", "productCreatedDateImg"]
                    );

                    $contentJson = jsonToArr($actuallyWorkOrderContentModel->content, []);
                    $resources = array_merge($contentJson, collect($resources)->map(function($val, $key)use($contentJson){
                        if(isset($contentJson[$key]) && !empty($contentJson[$key]) && empty($val)){
                            $val = $contentJson[$key];
                        }
                        return $val;
                    })->toArray());

                    $getImgFunc = function(string $field)use($resources){
                        return collect(attributeGet($resources, $field, []))->implode(PHP_EOL);
                    };

                        array_push(
                            $tempCommonExcelContents,
                            $errJdeCodes, //问题产品
                            $goodsCode,   //商品编码
                            $goodsTagName,//统一名称
                            $actuallyWorkOrderContentModel ? WorkOrderApplyContentModel::getContent($actuallyWorkOrderContentModel)
                                ->get("manufactureTime", "") : "",//问题产品生产日期
                            $actuallyWorkOrderContentModel ? WorkOrderApplyContentModel::getContent($actuallyWorkOrderContentModel)
                                ->get("errNum", 0) : 0,
                            $actuallyWorkOrderContentModel ? WorkOrderApplyContentModel::getContent($actuallyWorkOrderContentModel)
                                                                                       ->get("errProductUnit", "") : "",
                            $actuallyWorkOrderContentModel ? WorkOrderApplyContentModel::getContent($actuallyWorkOrderContentModel)
                                ->get("problemDesc", "") : "",
                            $getImgFunc("arrivalNoteImg"),
                            $getImgFunc("productAbnormalImg"),
                            $getImgFunc("productInnerLabelImg"),
                            $getImgFunc("productCreatedDateImg"),
                            $factoryName,//生产厂家
                        );
                    } else {
                        array_push(
                            $tempCommonExcelContents,
                            $errJdeCodes,//问题产品
                            $actuallyWorkOrderContentModel ? WorkOrderApplyContentModel::getContent($actuallyWorkOrderContentModel)
                                ->get("errNum", 0) : 0,
                            $actuallyWorkOrderContentModel ? WorkOrderApplyContentModel::getContent($actuallyWorkOrderContentModel)
                                ->get("problemDesc", "") : "",
                            $factoryName,//生产厂家
                        );
                    }
                    break;
                case OrderEnum::PROBLEM_PID_4:

                    // 故障详情
                    $problemDescId   = $actuallyWorkOrderContentModel ? WorkOrderApplyContentModel::getContent($actuallyWorkOrderContentModel)
                        ->get('problemDescId', 0) : 0;
                    $config          = ConfigModel::getSingleConfig(
                        'workOrder',
                        'childDescConfig',
                        function ($data) {
                            return json_decode($data, true);
                        },
                        getSwitchCacheTime(3600)
                    );
                    $config          = collect($config)->where('problemPid', OrderEnum::PROBLEM_PID_4)->first()['data'] ?? [];
                    $problemDescText = $config[$v->problemChildId][$problemDescId] ?? '';

                    array_push(
                        $tempCommonExcelContents,
                        $problemDescText,
                        $actuallyWorkOrderContentModel ? WorkOrderApplyContentModel::getContent($actuallyWorkOrderContentModel)
                                                                                   ->get("installTime", 0) : 0,
                        $actuallyWorkOrderContentModel ? WorkOrderApplyContentModel::getContent($actuallyWorkOrderContentModel)
                                                                                   ->get("problemDesc", "") : "-",
                        $actuallyWorkOrderContentModel ? WorkOrderApplyContentModel::getContent($actuallyWorkOrderContentModel)
                                                                                   ->get("isAffect",
                                                                                       "") ? "影响" : "不影响" : "-",
                    );
                    if (
                        in_array(OrderEnum::PROBLEM_PID_4_CHILDREN_1, $this->problemChildIdsArr) ||
                        in_array(OrderEnum::PROBLEM_PID_4_CHILDREN_13, $this->problemChildIdsArr) ||
                        in_array(OrderEnum::PROBLEM_PID_4_CHILDREN_2, $this->problemChildIdsArr)
                    ) {
                        //生产厂家 选择框有数据时
                        $chooseFactory = WorkOrderApplyContentModel::getContent($actuallyWorkOrderContentModel)
                            ->get("chooseFactory", []);
                        $factoryName   = '';
                        if ($chooseFactory) {
                            $factory     = ProblemFeedbackService::getOrmSupplier(); //查询所有厂家信息
                            $factory     = array_column($factory, 'text', 'value');
                            $tempFactory = [];
                            foreach ($chooseFactory as $chooseFactoryValue) {
                                $tempFactory[] = $factory[$chooseFactoryValue] ?? '其他';//供应商名称
                            }
                            $factoryName = implode(',', array_unique($tempFactory));
                        }
                        $deviceName         = WorkOrderApplyContentModel::getContent($actuallyWorkOrderContentModel)
                                ->get("deviceName", '') ?? '';
                        $deviceCreateTime   = WorkOrderApplyContentModel::getContent($actuallyWorkOrderContentModel)
                                ->get("deviceCreateTime", '') ?? '';
                        $deviceDeliveryTime = WorkOrderApplyContentModel::getContent($actuallyWorkOrderContentModel)
                                ->get("deviceDeliveryTime", '') ?? '';
                        if (!$deviceName) {
                            switch (WorkOrderApplyContentModel::getContent($actuallyWorkOrderContentModel)
                                    ->get("problemChildId", 0) ?? 0) {
                                case OrderEnum::PROBLEM_PID_4_CHILDREN_1:
                                    $goodsNames = '炸炉';
                                    break;
                                case OrderEnum::PROBLEM_PID_4_CHILDREN_2:
                                    $goodsNames = '展示柜';
                                    break;
                                case OrderEnum::PROBLEM_PID_4_CHILDREN_13:
                                    $goodsNames = '净水器';
                                    break;
                                default:
                                    $goodsNames = '';
                            }
                            if ($goodsNames) {
                                // 订货订单列表
                                $list = ProblemFeedbackWebService::getEquipmentDeliveryList($v->shopId, $goodsNames);
                                if (!empty($list)) {
                                    $deviceName = $list['goodsNames'] ?? "";
                                    if (!$deviceCreateTime) {
                                        $deviceCreateTime = $list['paidAt'] ? date('Y-m-d', strtotime($list['paidAt'])) : null;
                                    }
                                    if (!$deviceDeliveryTime) {
                                        $deviceDeliveryTime = $list['createdAt'] ? date('Y-m-d', strtotime($list['createdAt'])) : null;
                                    }
                                    $factoryName = $list['supplierName'] ?? '其他';
                                }
                            }
                        }
                        array_push($tempCommonExcelContents, $deviceName, $factoryName, $deviceCreateTime, $deviceDeliveryTime);
                    }
                    break;
                case OrderEnum::PROBLEM_PID_5:
                    if ($problemChildId != OrderEnum::PROBLEM_PID_5_CHILDREN_105) {//夸父收银进件2.0
                        array_push(
                            $tempCommonExcelContents,
                            $actuallyWorkOrderContentModel ? WorkOrderApplyContentModel::getContent($actuallyWorkOrderContentModel)
                                ->get("expectOpenTime", 0) : 0
                        );
                    }

                    break;
                case OrderEnum::PROBLEM_PID_6:
                case OrderEnum::PROBLEM_PID_7:
                case OrderEnum::PROBLEM_PID_8:
                case OrderEnum::PROBLEM_PID_9:
                case OrderEnum::PROBLEM_PID_10:
                    $customerAccepted        = $actuallyWorkOrderContentModel ? WorkOrderApplyContentModel::getContent($actuallyWorkOrderContentModel)
                        ->get("customerAccepted", '') : 0;
                    $problemAccepted         = $actuallyWorkOrderContentModel ? WorkOrderApplyContentModel::getContent($actuallyWorkOrderContentModel)
                        ->get("problemAccepted", '') : 0;
                    $tempCommonExcelContents = [
                        date('Y-m-d', $v->createdAt->timestamp),
                        $shopCode . $shopName,
                        OpenShopContractTemplateModel::MODE_MAP_TEXT[attributeGet($actuallySignOrder, "contractRel.mode",0)] ?? "-",
                        $this->shopInfos[$v->shopId]['shopMobile'] ?? '',
                        WorkOrderApplyMainModel::SOURCE_TYPE_TEXT[$v->sourceType] ?? "",
                        $v->problemPidText,
                        $actuallyWorkOrderContentModel ? WorkOrderApplyContentModel::getContent($actuallyWorkOrderContentModel)
                            ->get("problemDesc", '') : '',
                        $workOrderUserRoleList[$problemAccepted]['name'] ?? "",
                        $actuallyWorkOrderContentModel ? WorkOrderApplyContentModel::getContent($actuallyWorkOrderContentModel)
                            ->get("problemSolution", '') : '',
                        $workOrderUserRoleList[$customerAccepted]['name'] ?? "",
                    ];
                    break;
            }

            if ($problemChildId != OrderEnum::PROBLEM_PID_5_CHILDREN_105) {//夸父收银进件2.0
                $applyManagerMapModel->where("workOrderNo", $v->workOrderNo)->map(function ($v) use (
                    &$tempCommonExcelContents
                ) {
                    $dealTime = $v->updatedAt->timestamp ? $v->updatedAt->timestamp : $v->submitTime;// 处理时间 没有修改时间取提交时间
                    array_push($tempCommonExcelContents, $v->managerName, formatDate($dealTime),
                        $v->solution);
                });
            }
            return $tempCommonExcelContents;
        })->values()->toArray();

        return collect([
            [OrderEnum::PROBLEM_PID_TEXT[$this->type] ?? '-'],
            [
                "时间范围",
                "{$this->submitTimeStart}-{$this->submitTimeEnd}"
            ],
            [
                "工单数量",
                $this->originalData->count()
            ],
            [
                "完成数量",
                $this->originalData->where("step", "=", MissionEnum::STEP_99)->count()
            ],
            $this->excelHeaders
        ])->merge($this->excelContents)->toArray();
    }

    public function generateExcelHeader(int $feedback, $problemChildId = 0)
    {
        switch ($this->type) {
            case OrderEnum::PROBLEM_PID_1:
                $this->excelHeaders = [
                    "序号",
                    "工单单号",
                    "工单状态",
                    "门店编号",
                    "门店名称",
                    "合同模式",
                    "加盟商",
                    "提交时间",
                    "督导名称",
                    "工单类型",
                    "问题类型",
                    "问题产品",
                    "问题产品数量",
                    "问题描述",
                    "供应商名称"
                ];
                break;
            case OrderEnum::PROBLEM_PID_2:
                $this->excelHeaders = [
                    "序号",
                    "工单单号",
                    "工单状态",
                    "门店编号",
                    "门店名称",
                    "合同模式",
                    "加盟商",
                    "提交时间",
                    "督导名称",
                    "工单类型",
                    "问题类型",
                    "问题产品",
                    "商品编码",
                    "统一名称",
                    "问题产品生产日期",
                    "问题产品数量",
                    "问题产品单位",
                    "问题描述",
                    "到货单图片",
                    "产品异常处照片",
                    "产品内袋标签图片",
                    "产品内袋生产日期图片",
                    "供应商名称"
                ];
                break;
            case OrderEnum::PROBLEM_PID_4:
                $this->excelHeaders = [
                    "序号",
                    "工单单号",
                    "工单状态",
                    "门店编号",
                    "门店名称",
                    "合同模式",
                    "加盟商",
                    "提交时间",
                    "督导名称",
                    "工单类型",
                    "问题类型",
                    '故障详情',
                    "安装日期",
                    "问题描述",
                    "是否影响营运"
                ];
                if (
                    in_array(OrderEnum::PROBLEM_PID_4_CHILDREN_1, $this->problemChildIdsArr) ||
                    in_array(OrderEnum::PROBLEM_PID_4_CHILDREN_13, $this->problemChildIdsArr) ||
                    in_array(OrderEnum::PROBLEM_PID_4_CHILDREN_2, $this->problemChildIdsArr)
                ) {
                    $this->excelHeaders = array_merge(
                        $this->excelHeaders, [
                            "设备名称",
                            "设备供应商",
                            "设备下单时间",
                            "设备发货时间",
                        ]
                    );
                }
                break;
            case OrderEnum::PROBLEM_PID_5:
                if ($problemChildId == OrderEnum::PROBLEM_PID_5_CHILDREN_105) {//夸父收银进件2.0
                    $this->excelHeaders = [
                        "录入时间",
                        "微信",
                        "支付宝",
                        "一二级绑定",
                        "绑定后台",
                        "开通状态",
                        "适用门店",
                        "商户名称",
                        "用户名",
                        "密码",
                        "商户号",
                        "交易密钥",
                        "订单前缀",
                        "合同模式"
                    ];
                } else {
                    $this->excelHeaders = [
                        "序号",
                        "工单单号",
                        "工单状态",
                        "门店编号",
                        "门店名称",
                        "合同模式",
                        "加盟商",
                        "提交时间",
                        "督导名称",
                        "工单类型",
                        "问题类型",
                        "期望开通时间"
                    ];
                }
                break;
            case OrderEnum::PROBLEM_PID_6:
            case OrderEnum::PROBLEM_PID_7:
            case OrderEnum::PROBLEM_PID_8:
            case OrderEnum::PROBLEM_PID_9:
            case OrderEnum::PROBLEM_PID_10:
                $this->excelHeaders = [
                    "日期",
                    "门店",
                    "合同模式",
                    "手机号",
                    "反馈渠道",
                    "问题类型",
                    "反馈内容",
                    "问题受理人",
                    "处理结果",
                    "客服受理人",
                ];
                break;
        }
        if ($problemChildId != OrderEnum::PROBLEM_PID_5_CHILDREN_105) {//夸父收银进件2.0
            for ($i = 0; $i < $feedback; $i++) {
                array_push($this->excelHeaders, "处理人", "处理时间", "处理方案");
            }
        }
    }

}
